package network

import (
	"encoding/binary"
	"math"
)

// 模拟c#中BinaryReader，不考虑越界问题(需要recover捕获错误)
type BytesReader struct {
	Bytes *[]byte
}

func (r *BytesReader) ReadByte() byte {
	b := (*r.Bytes)[0]
	*r.Bytes = (*r.Bytes)[1:]
	return b
}

func (r *BytesReader) ReadUint16() uint16 {
	b := (*r.Bytes)[:2]
	*r.Bytes = (*r.Bytes)[2:]
	return binary.LittleEndian.Uint16(b)
}

func (r *BytesReader) ReadUint32() uint32 {
	b := (*r.Bytes)[:4]
	*r.Bytes = (*r.Bytes)[4:]
	return binary.LittleEndian.Uint32(b)
}

func (r *BytesReader) ReadUint64() uint64 {
	b := (*r.Bytes)[:8]
	*r.Bytes = (*r.Bytes)[8:]
	return binary.LittleEndian.Uint64(b)
}

func (r *BytesReader) ReadUint8() uint8 {
	return uint8(r.ReadByte())
}

func (r *BytesReader) ReadInt8() int8 {
	return int8(r.ReadByte())
}

func (r *BytesReader) ReadInt16() int16 {
	return int16(r.ReadUint16())
}

func (r *BytesReader) ReadInt32() int32 {
	return int32(r.ReadUint32())
}

func (r *BytesReader) ReadInt64() int64 {
	return int64(r.ReadUint64())
}

func (r *BytesReader) ReadFloat32() float32 {
	return math.Float32frombits(r.ReadUint32())
}

func (r *BytesReader) ReadFloat64() float64 {
	return math.Float64frombits(r.ReadUint64())
}

func (r *BytesReader) ReadBool() bool {
	return r.ReadByte() != 0
}

func (r *BytesReader) ReadString() string {
	b := int((*r.Bytes)[0])
	s := string((*r.Bytes)[1 : b+1])
	*r.Bytes = (*r.Bytes)[b+1:]
	return s
}

//copy新拷贝
func (r *BytesReader) ReadBytes(n int) []byte {
	b := make([]byte, n)
	copy(b, (*r.Bytes))
	*r.Bytes = (*r.Bytes)[n:]
	return b
}

//切片方式
func (r *BytesReader) GetBytes(n int) []byte {
	b := (*r.Bytes)[:n]
	*r.Bytes = (*r.Bytes)[n:]
	return b
}
